<template>
  <view class="h-100vh flex flex-col bg-white">
    <S1Header title="批量下单" :on-back="goBack" />

    <!-- 买家选择区域 -->
    <view
      class="flex flex-shrink-0 items-center justify-between border-b border-b-#eee border-b-solid bg-white px-30rpx"
    >
      <view class="w-500rpx flex flex-1 items-center">
        <scroll-view scroll-x class="h-110rpx whitespace-nowrap lh-110rpx">
          <view
            v-for="(buyer, index) in buyerList" :key="index" class="relative mr-20rpx inline-block"
            @tap="selectBuyer(index)"
          >
            <view
              class="h-66rpx flex items-center justify-center rd-12rpx px-16rpx" :class="[
                selectedBuyerIndex === index
                  ? 'bg-#43CF7C c-white'
                  : 'bg-#f0f0f0 c-#333 border border-solid border-#e0e0e0',
              ]"
            >
              <text class="fz-28rpx">
                {{ buyer.name }}{{ buyer.sort ? `(${buyer.sort})` : '' }}
              </text>
            </view>
            <view
              v-if="buyer.car_num && buyer.car_num > 0"
              class="absolute right-0 top-0 h-32rpx w-32rpx flex translate-x-1/2 items-center justify-center rd-50% bg-#EB0E0E -translate-y-1/2"
            >
              <text class="fz-18rpx c-white">
                {{ buyer.car_num }}
              </text>
            </view>
            <view
              v-if="selectedBuyerIndex === index"
              class="absolute left-0 right-0 top-58rpx z-10 flex justify-center"
            >
              <view
                class="h-0 w-0 border-l-15rpx border-r-15rpx border-t-15rpx border-l-transparent border-r-transparent border-t-#43CF7C border-l-solid border-r-solid border-t-solid"
              />
            </view>
          </view>
        </scroll-view>
      </view>
      <view class="mt-5rpx h-60rpx w-100rpx flex items-center justify-center rd-8rpx" @tap="onAddBuyer">
        <img src="https://ceshiweb.picaime.com/static/images/cart/addMore.png" alt="" class="h-60rpx w-60rpx">
      </view>
    </view>

    <view class="flex flex-1 justify-center border-t border-t-#eee border-t-solid py-10rpx">
      <!-- 左侧输入区域 -->
      <view class="mr-10px h-550px w-143px flex flex-col overflow-hidden border border-#05b050 border-solid">
        <textarea
          v-model="entryText" class="box-border w-full flex-1 border-none p-10rpx"
          placeholder="请输入下单内容例：黄瓜1斤，青椒3件，苹果10斤，龙虾15斤."
          placeholder-style="font-size: 16px; font-weight: 400; letter-spacing: 0px; color: rgba(128, 128, 128, 1);"
          @input="onTextInput"
        />
      </view>

      <!-- 右侧结果区域 -->
      <view class="h-550px w-207px flex flex-col overflow-hidden border border-#05b050 border-solid">
        <view class="h-50rpx border-b border-b-#eee border-b-solid bg-white">
          <view class="h-full flex items-center">
            <view
              class="fz-14px h-50rpx w-35rpx overflow-visible whitespace-normal pl-5rpx text-left text-left c-black lh-50rpx"
            >
              序
            </view>
            <view
              class="fz-14px flex-1.5 h-50rpx overflow-visible whitespace-normal pl-10rpx text-left text-left c-black lh-50rpx"
            >
              货品信息
            </view>
            <view
              class="fz-14px h-50rpx flex-1 overflow-visible whitespace-normal pl-10rpx text-left text-left c-black lh-50rpx"
            >
              数量
            </view>
            <view
              class="fz-14px h-50rpx w-70rpx justify-center overflow-visible whitespace-normal p-0 text-left c-black lh-50rpx"
            >
              操作
            </view>
          </view>
        </view>

        <!-- 结果内容 -->
        <view class="flex-1 overflow-y-auto">
          <view v-if="parsedItems.length === 0" class="h-full flex flex-col items-center justify-center">
            <image
              class="mb-20rpx h-200rpx w-200rpx" src="https://ceshiweb.picaime.com/static/images/home/empty.png"
              mode="widthFix"
            />
            <text class="fz-28rpx text-center c-#999">
              暂无数据...
            </text>
          </view>

          <view v-else>
            <view
              v-for="(item, index) in parsedItems" :key="index"
              class="h-80rpx flex items-center border-b border-b-#f5f5f5 border-b-solid"
            >
              <view class="fz-16px w-35rpx pl-5rpx text-left fw-500" :class="item.goods_id ? 'c-#4caf50' : 'c-#ff5252'">
                {{ index + 1 }}.
              </view>
              <view
                class="fz-16px flex-1.5 overflow-hidden text-ellipsis whitespace-normal pl-10rpx text-left fw-500"
                :class="item.goods_id ? 'c-#4caf50' : 'c-#ff5252'"
              >
                {{ item.goods_name }}
              </view>
              <view class="fz-16px flex-1 pl-10rpx text-left fw-500" :class="item.goods_id ? 'c-#4caf50' : 'c-#ff5252'">
                {{ item.num }}{{ item.unit }}
              </view>
              <view class="w-70rpx flex justify-center">
                <view
                  class="h-60rpx w-60rpx flex cursor-pointer items-center justify-center rd-8rpx c-white"
                  @tap="removeItem(index)"
                >
                  <text class="fz-24rpx">
                    🗑️
                  </text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部按钮区域 -->
    <view class="w-full flex flex-col border-t border-t-#eaeaea border-t-solid bg-white pb-40rpx">
      <view class="fz-26rpx flex cursor-pointer items-center px-30rpx py-15rpx c-#333" @tap="toggleOrderOption">
        <view
          class="fz-22rpx mr-10rpx h-36rpx w-36rpx flex items-center justify-center border-2 border-#00c853 rd-50% border-solid fw-bold" :class="[
            orderToStorage ? 'bg-#00c853 c-white' : 'c-transparent',
          ]"
        >
          <text v-if="orderToStorage">
            ✓
          </text>
        </view>
        <text>下单到存单中心</text>
      </view>

      <view class="flex justify-between px-30rpx">
        <view
          class="fz-28rpx h-70rpx w-22% flex cursor-pointer items-center justify-center border border-#ff3b30 rd-8rpx border-solid bg-white c-#ff3b30 fw-500"
          @tap="clearAll"
        >
          清空
        </view>
        <view
          class="fz-28rpx h-70rpx w-22% flex cursor-pointer items-center justify-center border border-#ff9500 rd-8rpx border-solid bg-white c-#ff9500 fw-500"
          @tap="pasteContent"
        >
          粘贴
        </view>
        <view
          class="fz-28rpx h-70rpx w-22% flex cursor-pointer items-center justify-center border border-#333 rd-8rpx border-solid bg-white c-#333 fw-500"
          @tap="identifyContent"
        >
          识别
        </view>
        <view
          class="fz-28rpx h-70rpx w-28% flex cursor-pointer items-center justify-center rd-8rpx bg-#00c853 c-white fw-500"
          @tap="submitOrder"
        >
          下单
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { formatData, getMaijiaCar, guadanData, kaidanDataCar } from '@/api/order';

// 输入文本内容
const entryText = ref('');

// 下单选项
const orderToStorage = ref(true);

// 买家相关
interface Buyer {
  id: number;
  name: string;
  maijia_id: number;
  admin_id?: number;
  guadan?: string | null;
  time?: string;
  shouyin_id?: number;
  car_num?: number;
  order_id?: number | null;
  type?: number;
  sort?: number | null;
  maijia?: {
    id: number;
    username: string;
  };
}

const buyerList = ref<Buyer[]>([]);
const selectedBuyerIndex = ref(0);

// 定义商品项的接口
interface ParsedItem {
  goods_name: string;
  num: string;
  unit: string;
  goods_id?: string;
  price?: number;
  contain?: number;
  mate?: number;
}

// 解析后的商品列表
const parsedItems = ref<ParsedItem[]>([]);

// 获取买家列表
const getMaiJiaList = async () => {
  try {
    const res = await getMaijiaCar();
    if (res.code === 200 && res.data) {
      // 更新买家列表
      if (res.data.data && Array.isArray(res.data.data)) {
        buyerList.value = res.data.data;
        if (buyerList.value.length > 0) {
          selectedBuyerIndex.value = 0;
        }
      }
    }
  }
  catch (error) {
    console.error('获取买家列表失败', error);
  }
};

// 选择买家
const selectBuyer = (index: number) => {
  selectedBuyerIndex.value = index;
};

// 添加买家
const onAddBuyer = () => {
  uni.navigateTo({
    url: '/pages/common/selectBuyer/index?car_id=0',
  });
};

// 切换下单选项
function toggleOrderOption() {
  orderToStorage.value = !orderToStorage.value;
}

// 解析输入文本
function parseInputText(text: string): ParsedItem[] {
  // 分割文本（按逗号、句号或换行符）
  const items = text.split(/[,，.。\n]+/).filter(item => item.trim() !== '');

  const result: ParsedItem[] = [];

  // 解析每个项目
  items.forEach((item) => {
    // 匹配商品名称和数量
    const match = item.match(/(.+?)(\d+)([斤|件公千克kg个箱]+)/i);

    if (match) {
      const goods_name = match[1].trim();
      const num = match[2];
      const unit = match[3];

      result.push({
        goods_name,
        num,
        unit,
      });
    }
  });

  return result;
}

// 文本输入事件
function onTextInput() {
  parsedItems.value = parseInputText(entryText.value);
}

// 清空所有内容
function clearAll() {
  entryText.value = '';
  parsedItems.value = [];
}

// 粘贴内容
async function pasteContent() {
  // 尝试从剪贴板获取内容
  try {
    const text = await uni.getClipboardData();
    if (text && text.data) {
      entryText.value = text.data;
      onTextInput();
    }
  }
  catch (error) {
    uni.showToast({
      title: '粘贴失败',
      icon: 'none',
    });
  }
}

// 识别内容并调用formatData接口
function identifyContent() {
  if (!entryText.value.trim()) {
    uni.showToast({
      title: '请输入内容',
      icon: 'none',
    });
    return;
  }

  // 检查是否选择了买家
  const selectedBuyer = buyerList.value[selectedBuyerIndex.value];
  if (!selectedBuyer) {
    uni.showToast({
      title: '请先选择买家',
      icon: 'none',
    });
    return;
  }

  uni.showLoading({
    title: '识别中...',
  });

  // 调用formatData接口
  formatData({
    maijia_id: selectedBuyer.maijia_id,
    bitchItems: entryText.value,
  })
    .then((res: any) => {
      uni.hideLoading();

      if (res && res.code === 200 && res.data) {
        // 成功获取数据
        parsedItems.value = res.data;
      }
      else {
        // 处理错误
        uni.showToast({
          title: res?.msg || '识别失败',
          icon: 'none',
        });
      }
    })
    .catch((error: any) => {
      uni.hideLoading();
      uni.showToast({
        title: '识别失败',
        icon: 'none',
      });
      console.error(error);
    });
}

// 移除商品项
function removeItem(index: number) {
  parsedItems.value.splice(index, 1);
  updateEntryText();
}

// 根据解析项更新输入文本
function updateEntryText() {
  entryText.value = parsedItems.value
    .map((item: ParsedItem) => `${item.goods_name}${item.num}${item.unit}`)
    .join('\n');
}

// 提交订单
async function submitOrder() {
  if (parsedItems.value.length === 0) {
    uni.showToast({
      title: '请先添加商品',
      icon: 'none',
    });
    return;
  }

  // 检查是否选择了买家
  const selectedBuyer = buyerList.value[selectedBuyerIndex.value];
  if (!selectedBuyer) {
    uni.showToast({
      title: '请先选择买家',
      icon: 'none',
    });
    return;
  }

  uni.showLoading({
    title: '下单中...',
  });

  try {
    const carIds: number[] = []; // 存储所有成功下单的 car_id
    let successCount = 0;
    let failCount = 0;

    // 循环调用 kaidanDataCar 接口，每个商品项单独调用
    for (let i = 0; i < parsedItems.value.length; i++) {
      const item = parsedItems.value[i];
      item.goods_info.editUsername = selectedBuyer.name;
      item.goods_info.editUsernameId = selectedBuyer.maijia_id;
      item.goods_info.editWeightData = item.num;

      try {
        const res = await kaidanDataCar(item.goods_info);

        if (res && res.code === 200 && res.data && res.data.car_id) {
          successCount++;
          carIds.push(res.data.car_id);
        }
        else {
          failCount++;
          console.error(`商品 ${item.goods_name} 下单失败:`, res?.msg);
        }
      }
      catch (itemError) {
        failCount++;
        console.error(`商品 ${item.goods_name} 下单异常:`, itemError);
      }
    }

    // 如果选中了"下单到存单中心"且有成功的订单，则调用 guadanData 接口
    if (orderToStorage.value && carIds.length > 0) {
      let guadanSuccessCount = 0;
      let guadanFailCount = 0;

      for (const carId of carIds) {
        try {
          const guadanRes = await guadanData({
            car_id: carId,
          });

          if (guadanRes && guadanRes.code === 200) {
            guadanSuccessCount++;
          }
          else {
            guadanFailCount++;
            console.error(`car_id ${carId} 挂单失败:`, guadanRes?.msg);
          }
        }
        catch (guadanError) {
          guadanFailCount++;
          console.error(`car_id ${carId} 挂单异常:`, guadanError);
        }
      }

      uni.hideLoading();

      // 显示综合结果
      if (successCount === parsedItems.value.length && guadanSuccessCount === carIds.length) {
        uni.showToast({
          title: '全部下单并挂单成功',
          icon: 'success',
        });
      }
      else if (successCount > 0) {
        uni.showToast({
          title: `下单成功${successCount}个，挂单成功${guadanSuccessCount}个`,
          icon: 'none',
        });
      }
      else {
        uni.showToast({
          title: '下单失败',
          icon: 'none',
        });
      }
    }
    else {
      uni.hideLoading();

      // 显示下单结果
      if (successCount === parsedItems.value.length) {
        uni.showToast({
          title: '全部下单成功',
          icon: 'success',
        });
      }
      else if (successCount > 0) {
        uni.showToast({
          title: `下单成功${successCount}个，失败${failCount}个`,
          icon: 'none',
        });
      }
      else {
        uni.showToast({
          title: '下单失败',
          icon: 'none',
        });
      }
    }

    // 如果有成功的订单，清空左侧输入框并延迟返回
    if (successCount > 0) {
      // 下单成功后不清空右侧内容，只清空左侧输入框
      entryText.value = '';

      // 延迟返回上一页
      setTimeout(() => {
        goBack();
      }, 1500);
    }
  }
  catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: '下单失败',
      icon: 'none',
    });
    console.error(error);
  }
}

// 返回上一页
function goBack() {
  uni.navigateBack();
}

// 更新买家列表处理函数
const handleUpdateBuyer = async (buyer: Buyer) => {
  // 调用getMaiJiaList刷新整个买家列表
  await getMaiJiaList();

  // 找到新添加的买家索引并选中它
  const newBuyerIndex = buyerList.value.findIndex((item: Buyer) => item.maijia_id === buyer.maijia_id);
  if (newBuyerIndex >= 0) {
    // 选中该买家
    selectBuyer(newBuyerIndex);
  }
};

// 页面加载时执行
onMounted(() => {
  // 获取买家列表
  getMaiJiaList();

  // 监听买家更新事件
  uni.$on('updateSelectedBuyer', handleUpdateBuyer);
});
</script>
